package cn.tjie.basic.interceptor;

import cn.tjie.basic.jwt.JwtUtils;
import cn.tjie.basic.jwt.RsaUtils;
import cn.tjie.user.domain.Logininfo;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token,从请求头里面
        String token = request.getHeader("token");
        //2.判断token是否有值
        if(token!=null) {
            //如果有token，就用公钥去解密
            try {
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                JwtUtils.getInfoFromToken(token, publicKey, Logininfo.class);
                //放行
                return true;
            } catch (ExpiredJwtException e) {
                //告诉浏览器我要给你响应一个json数据，编码集为utf-8
                response.setContentType("application/json;charset=UTF-8");
                //向前端响应json数据---是一个对象--告诉前端过期了
                response.getWriter().println("{\"success\":false,\"message\":\"timeout\"}");
                //拦截
                return false;
            }
        }
        //跳转到登录页面 - 后端跳不了，因为后端项目没有页面 - 放在前端跳转
        //告诉浏览器我要给你响应一个json数据，编码集为utf-8
        response.setContentType("application/json;charset=UTF-8");
        //向前端响应json数据---是一个对象
        response.getWriter().println("{\"success\":false,\"message\":\"noLogin\"}");
        //拦截
        return false;
    }
}
